import wave
import struct
import matplotlib.pyplot as plt

def read_wav_file(file_path):
    """读取WAV文件的采样数据和参数"""
    with wave.open(file_path, 'rb') as wav_file:
        # 获取音频参数
        n_channels = wav_file.getnchannels()      # 声道数
        sample_width = wav_file.getsampwidth()    # 采样宽度（字节）
        frame_rate = wav_file.getframerate()       # 采样率（Hz）
        n_frames = wav_file.getnframes()           # 总帧数
        duration = n_frames / frame_rate           # 时长（秒）

        # 读取所有帧数据
        frames = wav_file.readframes(n_frames)

        # 将二进制数据转换为整数列表
        if sample_width == 2:  # 16-bit PCM
            fmt = '<{}h'.format(n_frames * n_channels)
            samples = list(struct.unpack(fmt, frames))
        else:
            raise ValueError("仅支持16-bit PCM格式的WAV文件。")

        # 如果是多声道，这里简单地取平均值（可以根据需要修改）
        if n_channels > 1:
            samples = [samples[i:i+n_channels] for i in range(0, len(samples), n_channels)]
            samples = [sum(channel)/n_channels for channel in samples]

        return {
            'n_channels': n_channels,
            'sample_width': sample_width,
            'frame_rate': frame_rate,
            'n_frames': n_frames,
            'duration': duration,
            'samples': samples
        }

def plot_waveform(samples, frame_rate):
    """绘制波形图"""
    time = [i / frame_rate for i in range(len(samples))]
    plt.figure(figsize=(10, 4))
    plt.plot(time, samples, color='b')
    plt.title('音频波形图')
    plt.xlabel('时间 (s)')
    plt.ylabel('振幅')
    plt.grid(True)
    plt.show()

def main():
    file_path = input("请输入WAV文件路径: ").strip()

    try:
        # 读取音频数据
        audio_data = read_wav_file(file_path)
        print(f"音频参数: {audio_data['n_channels']}声道, {audio_data['frame_rate']}Hz, 时长: {audio_data['duration']:.2f}秒")

        # 绘制波形图
        plot_waveform(audio_data['samples'], audio_data['frame_rate'])

    except Exception as e:
        print(f"错误: {e}")

if __name__ == "__main__":
    main()
